#include "pm/task.h"

using namespace pm;

const wxString Task::TABLE_NAME   = wxT("tasks");


Task::Task()
: db::Table()
, unit_cost(0)
, quantity(0)
{
}

Task::Task(wxSQLite3ResultSet& res)
: db::Table (res)
, name      (res, wxT("name"))
, unit_cost (res, wxT("unit_cost"))
, quantity  (res, wxT("quantity"))
, end_date  (res, wxT("end_date"))
, id_project(res, wxT("id_project"))
, id_tag    (res, wxT("id_tag"), db::ID::undefined)
{
}

db::update_value_t Task::prepare_insert(wxSQLite3Database& db)
{
	if (id_project.valid() == false) {
		return db::update_value_t(false, wxSQLite3Statement());
	}
	
	wxSQLite3Statement stmt = db.PrepareStatement("insert into tasks values(null, ?, ?, ?, ?, ?, ?)");
	stmt.Bind(1, name());
	stmt.Bind(2, unit_cost());
	stmt.Bind(3, quantity());
	stmt.BindDate(4, end_date());
	stmt.Bind(5, id_project());
	if (id_tag.valid()) {
		stmt.Bind(6, id_tag());
	} else {
		stmt.BindNull(6);
	}
	return db::update_value_t(true, stmt);
}

db::update_value_t Task::prepare_update(wxSQLite3Database& db)
{
	if (id_project.valid() == false) {
		return db::update_value_t(false, wxSQLite3Statement());
	}
	
	wxSQLite3Statement stmt = db.PrepareStatement("update tasks set name = ?, unit_cost = ?, quantity = ?, end_date = ?, id_project = ?, id_tag = ? where id = ?");
	stmt.Bind(1, name());
	stmt.Bind(2, unit_cost());
	stmt.Bind(3, quantity());
	stmt.BindDate(4, end_date());
	stmt.Bind(5, id_project());
	stmt.Bind(6, id_tag());
	stmt.Bind(7, id());
	return db::update_value_t(true, stmt);
}



GetTasksByProject::GetTasksByProject(const db::ID& idProject)
: id_project(idProject)
{
}

wxSQLite3Statement GetTasksByProject::prepare(wxSQLite3Database& db)
{
	wxSQLite3Statement stmt = db.PrepareStatement("select id, name, unit_cost, quantity, end_date, id_project, id_tag from tasks where id_project = ? order by end_date asc");
	stmt.Bind(1, id_project());
	return stmt;
}


GetTasksTodoByProject::GetTasksTodoByProject(const db::ID& idProject)
: GetTasksByProject(idProject)
{
}

wxSQLite3Statement GetTasksTodoByProject::prepare(wxSQLite3Database& db)
{
	wxSQLite3Statement stmt = db.PrepareStatement("select id, name, unit_cost, quantity, end_date, id_project, id_tag from tasks where id_project = ? and quantity != 0 order by end_date asc");
	stmt.Bind(1, id_project());
	return stmt;
}


GetTasksDoneByProject::GetTasksDoneByProject(const db::ID& idProject)
: GetTasksByProject(idProject)
{
}

wxSQLite3Statement GetTasksDoneByProject::prepare(wxSQLite3Database& db)
{
	wxSQLite3Statement stmt = db.PrepareStatement("select id, name, unit_cost, quantity, end_date, id_project, id_tag from tasks where id_project = ? and quantity == 0 order by end_date asc");
	stmt.Bind(1, id_project());
	return stmt;
}
